package backend.Instruction;

import backend.component.RISCVimm;
import backend.Register.RISCVoperand;
import backend.Register.physicalFReg;
import backend.Register.virtualFReg;

import java.util.ArrayList;
import java.util.List;

public class RISCVmove extends RISCVinst {
    private List<RISCVoperand> operands = new ArrayList<>();
    private boolean needChange = false;
    private String type;

    public String type() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public RISCVmove(List<RISCVoperand> operands) {
        this.operands = operands;
        setDst(operands.get(0));
        setSrc(operands.get(1));
    }

    public RISCVmove(List<RISCVoperand> operands,String type) {
        this.operands = operands;
        this.type = type;
    }

    public void setDst(RISCVoperand dst) {
        setDefReg(operands.get(0), dst);
        operands.set(0, dst);
    }

    public void setSrc(RISCVoperand src) {
        addUseReg(operands.get(1), src);
        operands.set(1, src);
    }

    public boolean getNeedChange() {
        return needChange;
    }

    public void setNeedChange() {
        needChange = true;
    }

    public RISCVoperand getDst() {
        return operands.get(0);
    }

    public RISCVoperand getSrc() {
        return operands.get(1);
    }

    @Override
    public void replaceReg(RISCVoperand oldReg, RISCVoperand newReg) {
        if (operands.get(0).equals(oldReg)) {
            setDst(newReg);
        }
        if (operands.get(1).equals(oldReg)) {
            setSrc(newReg);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        // 判断操作数列表中第二个操作数的类型
        if (operands.get(1) instanceof physicalFReg || operands.get(1) instanceof virtualFReg) {
            // 则选择使用浮点寄存器的指令 "fmv.s"（浮点寄存器的移动）
            sb.append("fmv.s ");
        } else if (operands.get(1) instanceof RISCVimm) {
            // 如果第二个操作数是立即数类型（RISCVimm）
            sb.append("li ");
        } else {
            // 如果第二个操作数既不是浮点寄存器，也不是立即数
            sb.append("move ");
        }
        sb.append(operands.get(0)).append(", ").append(operands.get(1));
        sb.append("\n");
        return sb.toString();
    }

}
